package com.coder.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.mapper.PermissionMapper;
import com.coder.rental.mapper.UserMapper;
import com.coder.rental.service.IPermissionService;
import com.coder.rental.utils.RouteTreeUtils;
import com.coder.rental.vo.RolePermissionVo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author renguren
 * @since 2025-04-04
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
    @Resource
    private UserMapper userMapper;

    @Override
    public List<Permission> selectPermissionListByUserId(Integer userId) {
        return baseMapper.selectPermissionListByUserId(userId);
    }

    @Override
    public List<Permission> selectList() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("order_num");
        List<Permission> permissions = baseMapper.selectList(queryWrapper);
        return RouteTreeUtils.buildMenuTree(permissions, 0);
    }

    @Override
    public List<Permission> selectTree() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("permission_type", 2);
        queryWrapper.orderByAsc("order_num");
        List<Permission> permissions = baseMapper.selectList(queryWrapper);
        Permission permission = new Permission();
        permission.setId(0).setPid(-1).setPermissionLabel("根目录");
        permissions.add(permission);
        return RouteTreeUtils.buildMenuTree(permissions, -1);
    }

    @Override
    public boolean hasChildren(Integer id) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid", id);
        return baseMapper.selectCount(queryWrapper) > 1;
    }

    /**
     * 选择权限树
     * <p>
     * 根据用户ID和角色ID，构建该用户的权限树，并查询角色原有的权限
     * 如果用户是管理员，查询所有权限信息；否则查询当前用户拥有的权限信息
     * 然后将这些权限信息封装到树形结构中，并找出角色原有的权限，放在一个数组中
     *
     * @param userId 用户ID，用于查询用户及其权限信息
     * @param roleId 角色ID，用于查询角色原有的权限信息
     * @return RolePermissionVo 包含权限树和角色原有权限的视图对象
     */
    @Override
    public RolePermissionVo selectPermissionTree(Integer userId, Integer roleId) {
        // 根据用户ID查询用户信息
        User user = userMapper.selectById(userId);
        List<Permission> list = null;
        // 如果用户是管理员，查询出所有权限信息
        if (user != null && user.getIsAdmin() == 1) {
            list = baseMapper.selectList(null);
        } else {
            // 否则查询出当前用户拥有的权限信息
            list = baseMapper.selectPermissionListByUserId(userId);
        }
        // 将登录用户所拥有的权限信息封装到树形结构中
        List<Permission> permissionList = RouteTreeUtils.buildMenuTree(list, 0);
        //  查询出要分配的角色原有的权限
        List<Permission> rolePermissionList = baseMapper.selectPermissionListByRoleId(roleId);
        // 找出包含的部分，放在Object[]数组中
        List<Permission> newList = new ArrayList<>();
        List<Integer> ids = new ArrayList<>(list.stream().map(Permission::getId).toList());
        List<Integer> ids1 = rolePermissionList.stream().map(Permission::getId).toList();
        ids.retainAll(ids1);
        Object[] array = ids.toArray();
        // 创建RolePermissionVo对象，将权限树和角色原有权限数组放入对象中
        RolePermissionVo rolePermissionVo = new RolePermissionVo();
        rolePermissionVo.setCheckedList(array).setPermissionList(permissionList);
        // 返回RolePermissionVo对象
        return rolePermissionVo;
    }
}
